import React, { Component } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio,
  Tooltip,
  Rate,
  Checkbox,
  Tag,
  Table,
} from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import StandardTable from '@/components/StandardTable';
import IconButton from '@/components/IconButton';
import ScrollSelect from '@/components/ScrollSelect';
import get from 'lodash/get';
import api from '@/api';
import numeral from 'numeral';

import styles from './OrderProfitLossAnalysis.less';

const FormItem = Form.Item;
const RangePicker = DatePicker.RangePicker;
const MaxExportItemNum = 60000; // 导出报表的阈值

@Form.create()
@connect(({ loading, dashboard }) => ({
  loading: loading.effects['dashboard/fetchOrderProfitLossAnalysis'],
  orderProfitLossAnalysis: dashboard.orderProfitLossAnalysis,
}))
class OrderProfitLossAnalysis extends Component {
  constructor(props) {
    super(props);
    this.state = {
      expandedRowKeys: [],
    };
  }

  componentDidMount() {
    this.fetchOrderProfitLossAnalysis({
      startTime: moment()
        .startOf('day')
        .subtract(30, 'days')
        .format('YYYY-MM-DD'),
      endTime: moment().format('YYYY-MM-DD HH:mm:ss'),
    });
  }

  columns = [
    {
      title: '序号',
      render: (text, record, index) => {
        return <span>{this.calcIndex(index)}</span>;
      },
    },
    {
      title: '客户',
      dataIndex: 'customerName',
    },
    {
      title: '订单号',
      dataIndex: 'waybillNo',
    },
    {
      title: '订单状态',
      dataIndex: 'orderStatusName',
    },
    {
      title: '产品服务',
      dataIndex: 'productName',
    },
    {
      title: '起止地',
      dataIndex: 'shortPath',
    },
    {
      title: '货物类型',
      dataIndex: 'cargoTypeName',
    },
    {
      title: '件数',
      dataIndex: 'packageNum',
    },
    {
      title: '实重(kg)',
      dataIndex: 'actualWeight',
    },
    {
      title: '计费重(kg)',
      dataIndex: 'feeWeight',
    },
    {
      title: '总计金额(CNY)',
      align: 'right',
      dataIndex: 'totalPrice',
      render: (text, record, index) => {
        return <span>{numeral(text).format('0,000.00')}</span>;
      },
    },
    {
      title: '应收(CNY)',
      align: 'right',
      dataIndex: 'saleTotal',
      render: (text, record, index) => {
        return <span>{numeral(text).format('0,000.00')}</span>;
      },
    },
    {
      title: '应付(CNY)',
      align: 'right',
      dataIndex: 'costTotal',
      render: (text, record, index) => {
        return <span>{numeral(text).format('0,000.00')}</span>;
      },
    },
    {
      title: '毛利(CNY)',
      align: 'right',
      dataIndex: 'grossProfit',
      render: (text, record, index) => {
        return <span>{numeral(text).format('0,000.00')}</span>;
      },
    },
    {
      title: '',
      width: '4%',
    },
    {
      title: '收货时间',
      dataIndex: 'receiveTime',
    },
    {
      title: '完成时间',
      dataIndex: 'finishedTime',
    },
  ];

  expandedRowRender = record => {
    const columns = [
      {
        title: '类型',
        dataIndex: 'type',
      },
      {
        title: '空运费',
        dataIndex: 'AFCFee',
      },
      {
        title: '燃油费',
        dataIndex: 'FSCFee',
      },
      {
        title: '提货费',
        dataIndex: 'PPCFee',
      },
      {
        title: '揽收费',
        dataIndex: 'PUCFee',
      },
      {
        title: '操作费',
        dataIndex: 'HDCFee',
      },
      {
        title: '配送费',
        dataIndex: 'DEFFee',
      },
      {
        title: '其他',
        dataIndex: 'OtherFee',
      },
      {
        title: '合计',
        dataIndex: 'Total',
      },
    ];

    const data = [1, 2].map(i => {
      const prefix = i == 1 ? 'sale' : 'cost';
      return {
        key: i,
        type: i == 1 ? '应收' : '应付',
        AFCFee: record[`${prefix}AFCFee`],
        FSCFee: record[`${prefix}FSCFee`],
        PPCFee: record[`${prefix}PPCFee`],
        PUCFee: record[`${prefix}PUCFee`],
        HDCFee: record[`${prefix}HDCFee`],
        DEFFee: record[`${prefix}DEFFee`],
        OtherFee: record[`${prefix}OtherFee`],
        Total: record[`${prefix}Total`],
      };
    });
    return (
      <div className={styles.customWidth}>
        <Table columns={columns} dataSource={data} pagination={false} />
      </div>
    );
  };

  onExpandedRowsChange = expandedRows => {
    this.setState({
      expandedRowKeys: expandedRows,
    });
  };

  calcIndex = index => {
    const { orderProfitLossAnalysis } = this.props;
    let currentPage = get(orderProfitLossAnalysis, 'pagination.currentPage') || 1;
    let pageSize = get(orderProfitLossAnalysis, 'pagination.pageSize') || 50;
    return (currentPage - 1) * pageSize + index + 1;
  };

  // 搜索栏获取客户
  queryCustomers = params => {
    return api.credit.queryCustomer({
      queryParams: params,
    });
  };
  // 搜索栏获取产品
  queryProducts = params => {
    return api.product.query({
      queryParams: params,
    });
  };
  // 搜索栏获取服务
  queryServices = params => {
    return api.service.query({
      queryParams: params,
    });
  };
  // 切换产品/服务
  handleRefTypeChange = () => {
    const { form } = this.props;
    form.resetFields('refId');
  };

  fetchOrderProfitLossAnalysis = ({ pageIndex = 1, pageSize = 50, ...rest } = {}) => {
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (fieldsValue.date && fieldsValue.date.length === 2) {
        fieldsValue.startTime = fieldsValue.date[0].startOf('day').format('YYYY-MM-DD');
        fieldsValue.endTime = fieldsValue.date[1].endOf('day').format('YYYY-MM-DD HH:mm:ss');
        delete fieldsValue.date;
      }
      if (fieldsValue.customerId) {
        fieldsValue.customerId = fieldsValue.customerId.key;
      }
      if (fieldsValue.refId) {
        if (fieldsValue.refType === '1') {
          fieldsValue.serviceId = fieldsValue.refId.key;
        } else if (fieldsValue.refType === '2') {
          fieldsValue.productId = fieldsValue.refId.key;
        }
        delete fieldsValue.refId;
      }
      if (fieldsValue.refType) {
        delete fieldsValue.refType;
      }
      let payload = {
        ...fieldsValue,
        pageIndex,
        pageSize,
        ...rest,
      };
      dispatch({
        type: 'dashboard/fetchOrderProfitLossAnalysis',
        payload: {
          queryParams: payload,
        },
      });
    });
    this.setState({
      expandedRowKeys: [],
    });
  };

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      pageIndex: pagination.current,
      pageSize: pagination.pageSize,
      ...filters,
    };
    if (sorter.field) {
      params.sort = `${sorter.field}`;
      params.asc = sorter.order === 'ascend';
    }
    this.fetchOrderProfitLossAnalysis(params);
  };

  handleSearch = e => {
    this.fetchOrderProfitLossAnalysis();
  };

  handleReset = e => {
    this.props.form.resetFields();
    this.handleSearch();
  };

  // 报表导出
  exportReport = event => {
    event.stopPropagation();
    const {
      orderProfitLossAnalysis: {
        pagination: { totalResult },
      },
    } = this.props;
    if (totalResult > MaxExportItemNum) {
      message.warning(`最多只能导出${MaxExportItemNum}条数据`);
      return;
    }
    const {
      form: { getFieldValue },
    } = this.props;
    let customerId = '';
    if (getFieldValue('customerId')) {
      customerId = `&customerId=${getFieldValue('customerId').key}`;
    }
    const startDate = getFieldValue('date')[0]
      .startOf('day')
      .format('YYYY-MM-DD');
    const endTime = getFieldValue('date')[1]
      .endOf('day')
      .format('YYYY-MM-DD HH:mm:ss');
    let idStr = '';
    if (getFieldValue('refId')) {
      if (getFieldValue('refType') === '2') {
        idStr = `&productId=${getFieldValue('refId').key}`;
      } else if (getFieldValue('refType') === '1') {
        idStr = `&serviceId=${getFieldValue('refId').key}`;
      }
    }
    window.location.href = `/api/v1/dashBoard/orderProfitLossAnalysis/down?startTime=${startDate}&endTime=${endTime}${customerId}${idStr}`;
  };

  render() {
    const { expandedRowKeys } = this.state;
    const {
      loading,
      orderProfitLossAnalysis,
      form: { getFieldDecorator, getFieldValue },
    } = this.props;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 19 },
      },
    };
    const refType = getFieldValue('refType');
    return (
      <PageHeaderWrapper title="损益分析">
        <Card bordered={false}>
          <div className={styles.tableListForm}>
            <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
              <Col md={8} sm={24}>
                <FormItem label="客户" {...formItemLayout}>
                  {getFieldDecorator('customerId')(
                    <ScrollSelect
                      search={this.queryCustomers}
                      allowClear
                      style={{ width: '100%' }}
                      onInput={e => maxLength(e, 15)}
                      placeholder="请输入客户名称或编码"
                      optionLabel="name"
                      optionKey="id"
                    />
                  )}
                </FormItem>
              </Col>

              <Col md={8} sm={24} style={{ height: 40, display: 'flex', alignItems: 'center' }}>
                {getFieldDecorator('refType', {
                  initialValue: '2',
                })(
                  <Select style={{ width: '35%' }} onChange={this.handleRefTypeChange}>
                    <Option value="1">服务</Option>
                    <Option value="2">产品</Option>
                  </Select>
                )}
                {refType === '2' &&
                  getFieldDecorator('refId')(
                    <ScrollSelect
                      allowClear
                      search={this.queryProducts}
                      style={{ width: '65%' }}
                      maxLength={15}
                      placeholder="请输入产品名称或编码"
                      optionKey="id"
                    />
                  )}
                {refType === '1' &&
                  getFieldDecorator('refId')(
                    <ScrollSelect
                      allowClear
                      search={this.queryServices}
                      style={{ width: '65%' }}
                      maxLength={15}
                      placeholder="请输入服务名称或编码"
                      optionKey="id"
                    />
                  )}
              </Col>
              <Col md={8} sm={24}>
                <FormItem label="完成日期" {...formItemLayout}>
                  {getFieldDecorator('date', {
                    initialValue: [
                      moment()
                        .startOf('day')
                        .subtract(30, 'days'),
                      moment().endOf('day'),
                    ],
                  })(
                    <RangePicker
                      allowClear={false}
                      style={{ width: '100%' }}
                      format="YYYY-MM-DD"
                      placeholder={['开始日期', '结束日期']}
                    />
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col>
                <Button style={{ float: 'right' }} onClick={this.handleReset}>
                  重置
                </Button>
                <Button
                  style={{ float: 'right', marginRight: 24 }}
                  type="primary"
                  loading={loading}
                  onClick={this.handleSearch}
                >
                  查询
                </Button>
              </Col>
            </Row>
          </div>
          <div style={{ minHeight: 32, marginBottom: 24 }}>
            {orderProfitLossAnalysis &&
              orderProfitLossAnalysis.list.length > 0 && (
                <IconButton
                  title="导出"
                  icon="icon-export"
                  onClick={this.exportReport}
                  style={{
                    color: '#1890ff',
                  }}
                />
              )}
          </div>
          <StandardTable
            rowKey="id"
            tableLayout="fixed"
            loading={loading}
            data={orderProfitLossAnalysis}
            columns={this.columns}
            expandedRowKeys={expandedRowKeys}
            onExpandedRowsChange={this.onExpandedRowsChange}
            expandedRowRender={this.expandedRowRender}
            onChange={this.handleStandardTableChange}
          />
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default OrderProfitLossAnalysis;
